package com.netrust.quarz.handle;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.fastjson.JSON;
import com.netrust.quarz.common.NetrustException;
import com.netrust.quarz.utils.http.ResultEnums;
import com.netrust.quarz.utils.http.ResultUtils;


@ControllerAdvice
public class ExceptionHandle {
	private static final Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
	
	@ExceptionHandler(value=Exception.class)
	public void handle(HttpServletResponse response,Exception e){
		if(e instanceof NetrustException){
			NetrustException ne=(NetrustException) e;
			this.outError(response, ne.getCode(), ne.getMessage());
			return;
		}
		this.outError(response,ResultEnums.error_500.getCode(),ExceptionUtils.getStackTrace(e));
		return;
	}
	
	
	private void outError(HttpServletResponse response,Integer code,String msg) { 
		try {
			String json = JSON.toJSONString(ResultUtils.error(code,msg));
			response.setCharacterEncoding("UTF-8");  
			response.setContentType("text/json");  
			ServletOutputStream os = response.getOutputStream();  
			os.write(json.getBytes("utf-8"));  			
		} catch (Exception e) {
			logger.error("【 异常】 {}", e);
		}
	 }  
}
